<template>
  <div>
    <h2>数据概览</h2>
    <div v-if="loading">加载中...</div>
    <div v-else>
      <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:16px;">
        <div class="card">建材总数：{{ materialsTotal }}</div>
        <div class="card">客户总数：{{ customersTotal }}</div>
        <div class="card">订单总数：{{ ordersTotal }}</div>
        <div class="card">总收入：¥ {{ revenueText }}</div>
      </div>
      <div ref="chartRef" style="height:360px;background:#fff;border:1px solid #ddd;border-radius:6px"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick, watch, computed } from 'vue'
import * as echarts from 'echarts'
import { http } from '../api/http'
import type { PageResult, Material, Customer, Order } from '../types'
const materialsTotal = ref(0)
const customersTotal = ref(0)
const ordersTotal = ref(0)
const loading = ref(false)
const chartRef = ref<HTMLDivElement | null>(null)
let chart: echarts.ECharts | null = null
const revenue = ref<number>(0)
const revenueText = computed(() => {
  return typeof revenue.value === 'number' ? revenue.value.toFixed(2) : '-'
})

async function fetchTotals() {
  loading.value = true
  try {
    const [m, c, o] = await Promise.all([
      http.get<PageResult<Material>>('/api/materials', { params: { page: 1, size: 1 } }),
      http.get<PageResult<Customer>>('/api/customers', { params: { page: 1, size: 1 } }),
      http.get<PageResult<Order>>('/api/orders', { params: { page: 1, size: 1 } })
    ])
    materialsTotal.value = m.data.total
    customersTotal.value = c.data.total
    ordersTotal.value = o.data.total
    const s = await http.get('/api/orders/summary')
    const rv = s.data?.revenue
    revenue.value = typeof rv === 'number' ? rv : Number(rv || 0)
  } finally {
    loading.value = false
    await nextTick()
    renderChart()
  }
}

function renderChart() {
  if (!chartRef.value) return
  if (!chart) chart = echarts.init(chartRef.value)
  const option: echarts.EChartsOption = {
    tooltip: { trigger: 'item' },
    legend: { bottom: 0 },
    series: [
      {
        type: 'pie',
        radius: '60%',
        data: [
          { name: '建材', value: materialsTotal.value },
          { name: '客户', value: customersTotal.value },
          { name: '订单', value: ordersTotal.value }
        ]
      }
    ]
  }
  chart.setOption(option)
}

function handleResize() {
  if (chart) chart.resize()
}

watch([materialsTotal, customersTotal, ordersTotal], renderChart)
onMounted(() => {
  fetchTotals()
  window.addEventListener('resize', handleResize)
})
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  if (chart) { chart.dispose(); chart = null }
})
</script>

<style>
.card { padding: 12px; border: 1px solid #ddd; border-radius: 6px }
</style>